
package com.directthought.elasticweb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jets3t.service.S3ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.security.AWSCredentials;

public class S3Copier {

	public static void main(String [] args) {
		if (args.length != 5) {
			System.err.println("usage: S3Copier <accessId> <secretKey> <bucket> [<key> <localFile>]|[<localFile> <key>]");
			System.exit(-1);
		}
		try {
			RestS3Service s3 = new RestS3Service(new AWSCredentials(args[0], args[1]));
			S3Bucket bucket = new S3Bucket(args[2]);
			S3Object obj = s3.getObject(bucket, args[3]);
			InputStream iStr = obj.getDataInputStream();
			OutputStream oStr = new FileOutputStream(new File(args[4]));
			byte [] buf = new byte[64*1024];
			int count;
			while ((count=iStr.read(buf)) != -1) {
				if (count > 0) {
					oStr.write(buf, 0, count);
				}
			}
			iStr.close();
			oStr.flush();
			oStr.close();
		} catch (Exception ex) {
			System.err.println("Error retrieving file: "+ex.getMessage());
		}
	}
}
